<?php
/*
客户管理
*/
//define('Acache_no','1');
class Con_customer extends Acan{
	public $defaultAct='my';
	public $Conread = '客户管理';
	public $Actread = array('list'=>'所有客户','my'=>'我的客户','info'=>'客户信息','pool'=>'客户池','pool_add'=>'添加为我的客户','import'=>'导入客户','import_list'=>'导入排版','import_save'=>'导入保存','save'=>'保存','del'=>'删除','delall'=>'删除所有','forgo'=>'放弃客户','change_client'=>'变更客户');
	function __construct($ainfo=null){
		parent::__construct($ainfo=null);
		if(empty($this->id) || $this->id == '*'){$this->id = '0';}
		$this->uid = Afun_uid();
		$this->model = Afun_db()->model(Acan_table_crm_customer);
		//print_r($this->model);
		$this->_S = Afun_session();
	}
	//--所有客户
	function Act_list(){
		$this->atitle = '所有客户';
		return $this->Act_my();
	}
	//--现货客户
	function Act_xianhuo(){
		$this->atitle = '现货客户';
		Afun_refresh('',$this->Amodr.'-list?xianhuo=1');
	}
	function Act_findall(){
		$this->atitle = '搜索结果';
		return $this->Act_my();
	}
	//--我的客户
	function Act_my(){
		if(empty($this->atitle)){$this->atitle = '我的客户';}
		$uid = $this->uid;
		if($this->id>1){
			$uid = $this->id;
		}
		if(is_array(Afun_new("qq")->enum())){
			$this->model->enum['uqq']=array_merge(array(''=>""),Afun_new("qq")->enum());//获取用户QQ枚举
		}else{
			$this->model->enum['uqq']=array(''=>"");
		}
		$this->model->enum['money'] = array_merge(array('0'=>'未知'),$this->model->enum['money']);
		$userkv = Afunc_user()->lists();$userkv[1]='系统';
		$this->model->enum['last_uid'] = $userkv;
		$this->model->enum['add_uid'] = $userkv;
		$obj = Afun_acan_new('list');
		$this->msms = Afun_db()->model(Acan_table_crm_sms);
		$coljson['sms'] = $obj->form_json($this->msms);
		$key_name = $this->model->key_name;
		$columnrr = $this->model->comment;//初始栏目
		$column_sop = Afun_arr_remove($this->model->comment,array('cid','source','uqq','money','xianhuo','last_uid','addtime','uptime','point','area','sign_time','sign_status','outlook','mark','about'));
		$columnrr = Afun_arr_remove($this->model->comment,array('source','point','mark','about'));
		$column = $obj->column($this->model,$columnrr,$_POST['acolumn']);
		$column_html = $obj->column_html($this->model,$column,'Aform');
		$this->model->comment['username'] = '所属用户';
		$column_json = $obj->form_json($this->model);
		$sign_status = array_merge(array(''=>'所有'),$this->model->enum['sign_status']);
		$where = $this->search($area_val,$post,$column_sop);
		$area_val = Ajson_encode($area_val);
		//分页函数
		if($this->Aact=='list' && $this->uid==$uid){
			if($this->id>0){
				$con->where = "a.uid=$uid".$where;
			}else{
				$con->where = "1".$where;
				if($this->_S['group']>1 && $this->_S['admin']==1){
					$adminjoin = " JOIN `".Acan_table_user_group."` g ON a.uid=g.uid";
					$con->where = "g.`group`=".$this->_S['group']." and g.appid=".Acan_app_id.$where;
				}
			}
		}else if($this->Aact=='list' && $this->uid!=$uid){
			$con->where = "a.uid=$uid".$where;
		}else if($this->Aact=='my'){
			$con->where = "a.uid=$this->uid".$where;//只能查看自己的客户
		}else if($this->Aact=='findall'){
			unset($column['cid']);
			$con->where = "1".$where;
		}
		$con->select = "a.*,b.username,s.sid";
		$page->theurl = $this->Aactr.'-'.$this->id;
		$page->by = $this->model->key_name;
		$page->page = '20';
		$con->join = "JOIN `".Acan_table_user."` b ON a.uid=b.uid".$adminjoin;
		if($_GET['sms']==1){
			$con->join .= " JOIN `".Acan_table_crm_sms."` s ON a.cid=s.cid";
		}else{
			$con->join .= " LEFT JOIN `".Acan_table_crm_sms."` s ON a.cid=s.cid";
		}
		$page->counts = $this->model->count($con);	//统计总数目
		$pages = Afun_apage($page);
		$con->order = "a.$pages->orderby";
		$con->limit = $pages->limit;
		//分页结束
		$list = $this->model->ofindAll($con);
		unset($con);
		if(is_array($list))
		foreach($list as $k=>$v){
			$listjson[$v->$key_name] = $v;
		}
		$listjson = Ajson_encode($listjson);
		if($this->Aact=='list'){
			include $this->Atpl($this->Amod.'/my');
		}else{
			include $this->Atpl();
		}
	}
	//--获取单用户信息
	function Act_info(){
		if($this->id<1){
			return;
		}
		$con->select = "a.*,b.username";
		$con->join = "LEFT JOIN `".Acan_table_user."` b ON a.uid=b.uid";
		$con->where = "a.cid=".$this->id;
		$info = $this->model->ofind($con);
		Afun_json($info);
	}
	//客户池
	function Act_pool_zhuce(){
		$this->atitle = '注册客户池';
		$total = $this->model->count("source=1 and uid is null");
		if($_POST){
			//--一定时间内添加数量限制
			$limit = '';
			$minute = Afunc_option('crm_pool_zhuce_minite')->get();//单位时间
			$maxadd = Afunc_option('crm_pool_zhuce_max')->get();//单位时间$minute分钟内人数
			$num = 0;
			$uct = Afun_cache_get('Acrm:pool_zhuce:'.$this->uid);
			$ntime = time();
			if(is_array($uct)){
				foreach($uct as $t=>$n){
					if(($ntime-$t) < 60*$minute){
						$num += $n;
					}else{
						unset($uct[$t]);//删除超时的
					}
				}
			}
			if($num>=$maxadd){
				Afun_refresh($minute.'分钟内添加用户超限，请稍后添加','referrer');return;
			}elseif($num==0){
				$limit = $maxadd;
			}else{
				$limit = $maxadd-$num;
			}
			$con->where = "source=1 and uid is null";
			$con->order = "import_time ASC";
			$con->limit = $limit;
			$rs = $this->model->update(array('uid'=>$this->uid,'import_time'=>Afun_get_time()),$con);
			if($rs>0){
				$uct[time()] = $rs;
				Afun_cache_set('Acrm:pool_zhuce:'.$this->uid,$uct,60*$minute);
			}
			Afun_refresh("添加成功 $rs 个注册客户",'referrer');return;
		}
		include $this->Atpl();
	}
	function Act_pool(){
		$this->atitle = '普通客户池';
		$where = " and source!=1";
		$obj = Afun_acan_new('list');
		$key_name = $this->model->key_name;
		$columnrr = $this->model->comment;//初始栏目
		$userkv = Afunc_user()->lists();$userkv[1]='系统';
		$this->model->enum['last_uid'] = $userkv;
		$this->model->enum['add_uid'] = $userkv;
		$column_sop = Afun_arr_remove($this->model->comment,array('cid','source','uqq','money','xianhuo','last_uid','addtime','uptime','point','area','sign_time','sign_status','outlook','mark','about'));
		$column_sop_time = Afun_arr_get($this->model->comment,array('addtime','uptime','import_time','active_time','last_time','sign_time'));
		unset($columnrr['cid']);
		$column = $obj->column($this->model,$columnrr,$_POST['acolumn']);
		$where .= $this->search($area_val,$post,$column_sop);
		//分页函数
		$con->where = "a.uid is null".$where;
		$con->select = "a.*";
		$page->theurl = $this->Aactr.'-'.$this->id;
		$page->by = $this->model->key_name;
		$page->page = '20';
		$page->counts = $this->model->count($con);	//统计总数目
		$pages = Afun_apage($page);
		$con->order = "a.$pages->orderby";
		$con->limit = $pages->limit;
		//分页结束
		$list = $this->model->findAll($con);
		$areac = Afunc_area();
		include $this->Atpl();
	}
	function Act_pool_add(){
		if($_POST){
			//--一定时间内添加数量限制
			$limit = '';
			$minute = Afunc_option('crm_pool_minite')->get();//单位时间
			$maxadd = Afunc_option('crm_pool_maxadd')->get();//单位时间$minute分钟内人数
			$num = 0;
			$uct = Afun_cache_get('Acrm:pool_add:'.$this->uid);
			$ntime = time();
			if(is_array($uct)){
				foreach($uct as $t=>$n){
					if(($ntime-$t) < 60*$minute){
						$num += $n;
					}else{
						unset($uct[$t]);//删除超时的
					}
				}
			}
			if($num>=$maxadd){
				Afun_refresh($minute.'分钟内添加用户超限，请稍后添加',$this->Amodr.'-pool');return;
			}elseif($num==0){
				$limit = "LIMIT $maxadd";
			}else{
				$limit = 'LIMIT '.($maxadd-$num);
			}
			//--
			$save = $_POST['save'];
			$num = count($save);
			foreach($save as $k=>$v){
				if(empty($cid)){
					$cid = $v;
				}else{
					$cid .= ','.$v;
				}
			}
			$rs = $this->model->update(array('uid'=>$this->uid,'import_time'=>Afun_get_time()),"uid is null and cid in ($cid)".$limit);
			
			if($rs>0){
				$uct[time()] = $rs;
				Afun_cache_set('Acrm:pool_add:'.$this->uid,$uct,60*$minute);
			}
			if(!$this->id){
				$this->id = $this->Amodr.'-pool';
			}
			Afun_refresh("选择的 $num 个客户，成功添加 $rs 个",$this->id);
		}else{
			Afun_refresh('请先选择用户',$this->Amodr.'-pool');
		}
	}
	//导入客户
	function Act_import(){
		$this->atitle = '导入客户';
		include $this->Atpl();
	}
	//导入客户栏目设定
	function Act_import_list(){
		$this->atitle = '客户数据栏目设定';
		$crm_source = Afunc_enum()->data('crm_source');
		$column = $this->model->comment;
		$column = Afun_arr_get($this->model->comment,array('realname','phone','tel','fax','qq','mail','identity','address','about','mark'));
		$column = array_merge(array(''=>'不保存'),$column);
		$dfcol = array('','realname','phone','mail','address','qq','mark');
		if($_POST){
			$path = A_ROOT.'/temp/crm/';
			$savepath = Afunc_file()->upfile('file',$path,true);
			$xls = Afun_acan_new('xls',$savepath);
			$data = $xls->getdata();
			include $this->Atpl();
		}else{
			Afun_refresh('请先上传文件',$this->Amodr.'-import');
		}
	}
	//客户导入结果
	function Act_import_save(){
		$this->atitle = '导入客户数据结果';
		$comment = $this->model->comment;
		if($_POST){
			$data = $_POST['save'];
			$sheets = $_POST['sheets'];
			$column = $_POST['column'];
			$source = $_POST['source'];
			if(is_array($sheets)){
				foreach ($sheets as $skey => $sheet) {
					if(!empty($sheet)){
						foreach($data[$skey] as $key=>$val){
							foreach($val as $k=>$v){
								if(empty($column[$skey][$k])){continue;}
								if($column[$skey][$k]=="mark"){
									$arr[$column[$skey][$k]] .= $v."\n";
								}else{
									$arr[$column[$skey][$k]] = $v;
								}
							}
							$arr['addtime'] = Afun_get_time();
							$arr['source'] = $source;
							$arr['add_uid'] = $this->uid;
							$rs[$skey][$key] = $this->model->save($arr);
							unset($arr['addtime'],$arr['source'],$arr['add_uid']);
							$data[$skey][$key] = $arr;
							unset($arr);
						}
					}
				}
			}
			include $this->Atpl();
		}else{
			Afun_refresh('请先上传文件',$this->Amodr.'-import');
		}
	}
	//变更客户资源
	function Act_change_client(){
		$this->atitle = '变更客户';
		if($_POST){
			$rs = 0;
			$post = $_POST;
			$upsave = array('uid'=>$post['in'],'import_time'=>Afun_get_time());
			if($post['out']){
				$uout = $post['out'];
				$rs = $this->model->update($upsave,"uid = $uout");
			}elseif($post['cids']){
				$cids = $post['cids'];
				if(is_array($cids)){
					foreach ($cids as $k => $v) {
						if(empty($uout)) $uout = $v;
						else $uout .= ','.$v;
					}
					$rs = $this->model->update($upsave,"cid in ($uout)");
				}
			}
			$msg = "成功变更 $rs 个客户";
			Afun_json($msg);
		}
		$con->select = "a.uid,a.username,b.group,c.title,COUNT(cs.cid) as customers";
		$con->join = "LEFT JOIN `".Acan_table_user_group."` b ON a.uid=b.uid LEFT JOIN `".Acan_table_group."` c ON b.group=c.gid and b.appid=c.appid LEFT JOIN `".Acan_table_crm_customer."` cs ON a.uid=cs.uid ";
		$con->where = "cs.uid>0 and b.appid=".Acan_app_id;
		$con->order = "b.group ASC";
		$con->group = "a.uid ASC";
		$users = Afun_db()->model(Acan_table_user)->findAll($con);
		foreach ($users as $k => $v) {
			$user[$v['group']]['title'] = $v['title'];
			$user[$v['group']]['user'][$v['uid']] = $v['username'].' --- '.$v['customers'].'个';
		}
		include $this->Atpl();
	}
	//批量更新
	function Act_save(){
		Afun_post_auth();
		$savedata = $_POST['save'];
		$savedata['uptime'] = Afun_get_time();
		if(isset($savedata['xianhuo'])){
			$savedata['xianhuo'] = $savedata['xianhuo'][0];
		}else{
			$savedata['xianhuo'] = 0;
		}
		if($savedata['sign_status']>0){
			$savedata['sign_time'] = Afun_get_time();
		}
		if($this->id == 'one'){
			$key = $savedata[$this->model->key_name];
			$savedata['last_uid'] = $this->uid;
			unset($savedata[$this->model->key_name]);
			if(!empty($key)){
				Afun_new("crm_log")->add($savedata,'up_cus',$key);
				$msg = $this->model->updatePk($savedata,$key);
			}else{//--添加一个新用户
				$savedata['uid'] = $this->uid;
				$savedata['add_uid'] = $this->uid;
				$savedata['import_time'] = $savedata['addtime'] = Afun_get_time();
				$msg = $this->model->save($savedata);
				$cid = $this->model->lastInsertId();
				Afun_new("crm_log")->add($savedata,'add_cus',$cid);
			}
		}elseif(is_array($savedata)){
			foreach($savedata as $i=>$vals){
				$this->model->updatePk($vals,$vals['key']);
			}
		}
		Afun_json($msg);
	}
	//删除
	function Act_del(){
		Afun_post_auth();
		$data = $this->model->findPk($this->id);
		if($data['add_uid']!=$this->uid){
			echo '你无权删除此客户';
			return;
		}
		if($this->model->deletePk($this->id)){
			Afunc_group()->usergroupdel($this->id);
			echo '删除成功';
		}
	}
	//删除所选
	function Act_delall(){
		Afun_post_auth();
		foreach($_POST['chk'] as $key=>$val){
			Afunc_group()->usergroupdel($val);
			if(empty($vala))
				$vala = "'$val'";
			else
				$vala .=",'$val'";
		}
		$where = " and add_uid=".$this->uid;
		$this->model->delete($this->model->key_name." IN ($vala)".$where);
		Afun_refresh("删除成功",'referrer');
	}
	//放弃客户
	function Act_forgo(){
		Afun_post_auth();
		$data = $this->model->findPk($this->id);
		$up = ",uptime='".Afun_get_time()."'";
		if($data['source']==1){//注册客户放弃时改为其它客户
			$up .= ",source=5";
		}
		$rs = $this->model->update('uid=null,last_uid='.$this->uid.$up,"cid=".$this->id);
		Afun_new("crm_log")->add('放弃客户:'.$data['realname'],'forgo_cus',$this->id);
		echo '放弃成功';
	}
	//搜索
	function search(&$area_val,&$post,$column_sop){
		if($_GET){
			$post = $_GET;
			$sign = false;$chi=false;
			if($post['source']=='zhuce'){
				$sign = true;
				$source = " and a.source=1";//网站注册来的客户
			}else{
				//$source = " and a.source>1";//导入的客户
			}
			if($post['xianhuo']=='1'){
				$chi=true;
				$where .= " and a.xianhuo=".$post['xianhuo'];
			}
			if($post['last_uid']>0){
				$sign = true;$chi=true;
				$where .= " and a.last_uid=".$post['last_uid'];
			}
			if($post['point']=='1'){
				$sign = true;$chi=true;
				$where .= " and a.point=".$post['point'];
			}
			if($post['outlook']){
				$sign = true;$chi=true;
				$where .= " and a.outlook=".$post['outlook'];//预计开户
			}
			if($post['lianxi']=='1'){
				$sign = true;$chi=true;
				$where .= " and (a.last_time>='".date('Y-m-d',Afun_get_time('time')-86400*6)."' and a.last_time<'".date('Y-m-d',Afun_get_time('time')+86400)."')";
			}elseif($post['lianxi']=='2'){
				$sign = true;$chi=true;
				$where .= " and (a.last_time>='".date('Y-m-d',Afun_get_time('time')-86400*30)."' and a.last_time<'".date('Y-m-d',Afun_get_time('time')-86400*6)."')";
			}elseif($post['lianxi']=='3'){
				$sign = true;$chi=true;
				$where .= " and a.last_time<'".date('Y-m-d',Afun_get_time('time')-86400*30)."'";
			}
			if($post['import_time']=='today'){
				$sign = true;$chi=true;
				$where .= " and (a.import_time>='".Afun_get_time("date")."' and a.import_time<'".date('Y-m-d',Afun_get_time("time")+86400)."')";
			}
			if($post['active_time']=='today'){
				$sign = true;$chi=true;
				$where .= " and (a.active_time>='".Afun_get_time("date")."' and a.active_time<'".date('Y-m-d',Afun_get_time("time")+86400)."')";
			}elseif($post['active_time']=='no'){
				$sign = true;$chi=true;
				$where .= " and a.active_time is null";
			}
			if($post['uqq']){
				$where .= " and a.uqq = ".$post['uqq']."";//所属QQ
			}
			if($post['country']){
				$zhizhen = "0";
				$area_val->$zhizhen = $post['country'];
			}
			if($post['sheng']){
				$zhizhen = "1";
				$area_val->$zhizhen = $post['sheng'];
			}
			if($post['shi']){
				$zhizhen = "2";
				$area_val->$zhizhen = $post['shi'];
			}
			if($post['shi']>1){
				$area = Ajson_encode($area_val);
				$where .= " and a.area = '$area'";
			}elseif($post['sheng']>1){
				$area = '{"0":"'.$post['country'].'","1":"'.$post['sheng'].'"';
				$where .= " and a.area LIKE '$area%'";
			}elseif($post['country']>0){
				$area = '{"0":"'.$post['country'].'"';
				$where .= " and a.area LIKE '$area%'";
			}
			if(!empty($post['search'])){
				$sop = $post['sop'];
				if($post['sop']!=''){
					$where .= " and a.".$post['sop']." LIKE '%".$post['search']."%'";
				}else{
					foreach($column_sop as $k=>$v){
						if(empty($whereop)){
							$whereop = "a.".$k." LIKE '%".$post['search']."%'";
						}else{
							$whereop .= " or a.".$k." LIKE '%".$post['search']."%'";
						}
					}
					if($whereop){
						$where .= " and (".$whereop.")";
					}
				}
			}
			if(strlen($post['sign_status'])>0){
				$status = " and a.sign_status = ".$post['sign_status']."";
			}else{
				if($sign)
					$status = " and a.sign_status = 0".$source;//未签约
			}
			if($chi==true && $this->Aact!='pool'){
				$status .= " and a.uid>1";
			}
			if($post['sop_time']){
				$field = $post['sop_time'];
				if(!empty($post['s_time'][0]) && !empty($post['s_time'][1]))
					$where .= " and (a.$field>='".$post['s_time'][0]."' and a.$field<'".$post['s_time'][1]."')";
				elseif(!empty($post['s_time'][0]))
					$where .= " and a.$field>='".$post['s_time'][0]."'";
				elseif(!empty($post['s_time'][1]))
					$where .= " and a.$field<'".$post['s_time'][1]."'";
			}
		}
		return $status.$where;
	}
}

?>